package channel;

import handler.HandlerSingleFactory;
import handler.HttpHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.logging.Handler;

/**
 * @author yuzk
 * @date 2018/1/15
 */
public class HttpChannelInitializer extends ChannelInitializer<SocketChannel>{

    Logger logger = LoggerFactory.getLogger(HttpChannelInitializer.class);
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //pipeline.addLast("decoder",new HttpRequestDecoder());
        /**usually we receive http message infragment,if we want full http message,
         * we should bundle HttpObjectAggregator and we can get FullHttpRequest。
         * 我们通常接收到的是一个http片段，如果要想完整接受一次请求的所有数据，我们需要绑定HttpObjectAggregator，然后我们
         * 就可以收到一个FullHttpRequest-是一个完整的请求信息。
         **/
        pipeline.addLast("servercodec",new HttpServerCodec());
        pipeline.addLast("aggegator",new HttpObjectAggregator(1024*1024*64));//定义缓冲数据量
//        pipeline.addLast(HandlerSingleFactory.getHttpHandle());
        pipeline.addLast(new HttpHandler());
//        pipeline.addLast(new ChannelInboundHandlerAdapter(){
//            @Override
//            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                DefaultFullHttpResponse response = (DefaultFullHttpResponse) msg;
//                response = (DefaultFullHttpResponse) response.replace(Unpooled.directBuffer().writeBytes("stupid".getBytes()));
//                logger.debug("the next handler's read method msg response is :  " + response.content().readableBytes());
//                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
//            }
//        });
       // pipeline.addLast("responseencoder",new HttpResponseEncoder());

    }
}
